package com.stx.jeepay.core.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.stx.jeepay.core.dao.SysRoleDao;
import com.stx.jeepay.core.entity.SysRoleEntRelaEntity;
import com.stx.jeepay.core.entity.SysRoleEntity;
import com.stx.jeepay.core.entity.SysUserRoleRelaEntity;
import com.stx.jeepay.core.expection.BizException;
import com.stx.jeepay.core.service.SysRoleEntRelaService;
import com.stx.jeepay.core.service.SysRoleService;
import com.stx.jeepay.core.service.SysUserRoleRelaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;


@Service("sysRoleService")
public class SysRoleServiceImpl extends ServiceImpl<SysRoleDao, SysRoleEntity> implements SysRoleService {

    @Autowired
    private SysUserRoleRelaService sysUserRoleRelaService;

    @Autowired
    private SysRoleEntRelaService sysRoleEntRelaService;

    /**
     * 根据用户查询全部角色集合
     * @param sysUserId
     * @return
     */
    @Override
    public List<String> findListByUser(Long sysUserId) {
        List<String> result = new ArrayList<>();
        // 根据用户ID查全性
        sysUserRoleRelaService.list(new LambdaQueryWrapper<SysUserRoleRelaEntity>().eq(SysUserRoleRelaEntity::getUserId,sysUserId))
                .stream().forEach(i->result.add(i.getRoleId()));
        return result;
    }

    @Transactional
    @Override
    public void removeRole(String roleId) {
        if(sysUserRoleRelaService.count(new LambdaQueryWrapper<SysUserRoleRelaEntity>()
                .eq(SysUserRoleRelaEntity::getRoleId, roleId)) > 0){
            throw new BizException("当前角色已分配到用户， 不可删除！");
        }

        //删除当前表
        removeById(roleId);

        //删除关联表
        sysRoleEntRelaService.remove(new LambdaQueryWrapper<SysRoleEntRelaEntity>()
                .eq(SysRoleEntRelaEntity::getRoleId, roleId));
    }
}